package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.Utils.PageUtil;
import com.example.haoqisystem.entity.Lecture;
import com.example.haoqisystem.entity.TrainningPlan;
import com.example.haoqisystem.request.CreateLectureRequest;
import com.example.haoqisystem.request.QueryLectureListRequest;
import com.example.haoqisystem.request.UpdateLectureRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.response.PageResult;
import com.example.haoqisystem.respository.LectureRepository;
import com.example.haoqisystem.respository.TrainningPlanRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ ={@Autowired} )
public class LectureService {
    private final LectureRepository lectureRepository;
    public final TrainningPlanRepository trainningPlanRepository;
    //增加课程
    public BaseResponse<Lecture> add(CreateLectureRequest request) {
        try{
            Lecture lecture=new Lecture();
            lecture.setIsNotificated(false);
            BeanUtil.copyProperties(request,lecture, CopyOptions.create().setIgnoreNullValue(true));
            Optional<TrainningPlan> planOptional=trainningPlanRepository.findById(request.getTrainningPlanId());
            //将对应课程存到培训计划里面
            Lecture lecture1= lectureRepository.save(lecture);
            if(planOptional.isPresent()){
                TrainningPlan plan=planOptional.get();
                plan.setLectureId(lecture1.getId());
                plan.setIsGenerateLecture(true);
                trainningPlanRepository.save(plan);
            }
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true,lecture1);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //删除课程
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<String> delete(Long id) {
        try {
            Optional<Lecture> lectureOptional=lectureRepository.findByIdAndDeletedFalse(id);
            if(!lectureOptional.isPresent()){
                return new BaseResponse<>(ConstUtil.DELETED_FALSE,false,"该课程不存在！");
            }
            Lecture lecture=lectureOptional.get();
            lecture.setDeleted(true);
            lectureRepository.save(lecture);
            //查找到对于对应的培训计划

            Optional<TrainningPlan> planOptional=trainningPlanRepository.findByIdAndDeletedFalse(lecture.getTrainningPlanId());
            if(planOptional.isPresent()){
                TrainningPlan plan=planOptional.get();
                plan.setIsGenerateLecture(false);
                trainningPlanRepository.save(plan);
            }
            return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,"删除成功！");
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,"删除失败！");
        }
    }

    //查看课程详情
    public BaseResponse<Lecture> detail(Long id,boolean deleted) {
        Optional<Lecture> lectureOptional= lectureRepository.findById(id);
        if(!lectureOptional.isPresent()){
            return new BaseResponse<>("该课程不存在！",false,null);
        }
        Lecture lecture=lectureOptional.get();
        if (lecture.getDeleted()!=deleted){
            return new BaseResponse<>("该课程不存在！",false,null);
        }
        return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,lecture);
    }

    //更新课程内容
    public BaseResponse<Lecture> update(UpdateLectureRequest request) {
        try{
            Optional<Lecture> lectureOptional= lectureRepository.findByIdAndDeletedFalse(request.getId());
            if (!lectureOptional.isPresent()){
                return new BaseResponse<>("该课程不存在！",false,null);
            }
            Lecture lecture=lectureOptional.get();
            BeanUtil.copyProperties(request,lecture,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true, lectureRepository.save(lecture));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //分页查询课程列表
    public BaseResponse<PageResult<Lecture>> queryList(QueryLectureListRequest request) {
        try{
            Specification<Lecture> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                if(request.getLectureName()!=null&&!request.getLectureName().equals("")){
                    String lectureNameLike="%"+request.getLectureName()+"%";
                    predicates.add(builder.like(root.get("lectureName"),lectureNameLike));
                }
                if(request.getLecturePlace()!=null&&!request.getLecturePlace().equals("")){
                    String lecturePlaceLike="%"+request.getLecturePlace()+"%";
                    predicates.add(builder.like(root.get("lecturePlace"),lecturePlaceLike));
                }
                if(request.getBetweenTime()!=null&&!request.getBetweenTime().equals("")){
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date beginTime = null;
                    Date endTime = null;
                    try {
                        beginTime = dateFormat.parse(request.getBetweenTime().substring(0, 10));
                        endTime = dateFormat.parse(request.getBetweenTime().substring(13));
                    } catch (ParseException e) {
                        // 处理日期解析异常
                        e.printStackTrace(); // 或者记录日志
                    }
                    predicates.add(builder.between(root.get("lectureTime"),beginTime,endTime));
                }
                predicates.add(builder.equal(root.get("deleted"),request.isDeleted()));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<Lecture> list= lectureRepository.findAll(specification);
            Collections.reverse(list);
            PageResult<Lecture> page= PageUtil.getPage(list,request.getPageNum(),request.getPageSize());
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,page);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //不分页列表
    public BaseResponse<List<Lecture>> queryList1(String lectureName,String betweenTime,
                                                  String lecturePlace,Boolean deleted) {
        try {
            Specification<Lecture> specification = (root, query, builder) -> {
                List<Predicate> predicates = new ArrayList<>();
                if (lectureName!= null && !lectureName.equals("")) {
                    String lectureNameLike = "%" + lectureName + "%";
                    predicates.add(builder.like(root.get("lectureName"), lectureNameLike));
                }
                if (lecturePlace != null && !lecturePlace.equals("")) {
                    String lecturePlaceLike = "%" + lecturePlace + "%";
                    predicates.add(builder.like(root.get("lecturePlace"), lecturePlaceLike));
                }
                if (betweenTime!= null && !betweenTime.equals("")) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date beginTime = null;
                    Date endTime = null;
                    try {
                        beginTime = dateFormat.parse(betweenTime.substring(0, 10));
                        endTime = dateFormat.parse(betweenTime.substring(13));
                    } catch (ParseException e) {
                        // 处理日期解析异常
                        e.printStackTrace(); // 或者记录日志
                    }
                    predicates.add(builder.between(root.get("lectureTime"), beginTime, endTime));
                }
                predicates.add(builder.equal(root.get("deleted"), deleted));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<Lecture> list = lectureRepository.findAll(specification);
            Collections.reverse(list);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS, true, list);
        } catch (Exception e) {
            return new BaseResponse<>(e.toString(), false, null);
        }
    }
}
